#!/bin/bash

# HTTP Server Test Script
# Author: Qoder
# Description: Simple test script for HTTP server functionality

echo "HTTP Server Test Script"
echo "======================"

SERVER_PORT=8080
SERVER_PID=""

# Function to start server
start_server() {
    echo "Starting HTTP server on port $SERVER_PORT..."
    ./http_server $SERVER_PORT &
    SERVER_PID=$!
    sleep 2
    
    if kill -0 $SERVER_PID 2>/dev/null; then
        echo "Server started successfully (PID: $SERVER_PID)"
        return 0
    else
        echo "Failed to start server"
        return 1
    fi
}

# Function to stop server
stop_server() {
    if [ ! -z "$SERVER_PID" ]; then
        echo "Stopping server (PID: $SERVER_PID)..."
        kill $SERVER_PID 2>/dev/null
        wait $SERVER_PID 2>/dev/null
        echo "Server stopped"
    fi
}

# Function to test endpoint
test_endpoint() {
    local url=$1
    local description=$2
    local method=${3:-GET}
    
    echo -n "Testing $description... "
    
    if command -v curl >/dev/null 2>&1; then
        if [ "$method" = "POST" ]; then
            response=$(curl -s -X POST -d '{"test":"data"}' -H "Content-Type: application/json" $url)
        else
            response=$(curl -s $url)
        fi
        
        if [ $? -eq 0 ] && [ ! -z "$response" ]; then
            echo "OK"
            echo "  Response: ${response:0:100}..."
        else
            echo "FAILED"
        fi
    else
        echo "SKIPPED (curl not available)"
    fi
}

# Main test execution
main() {
    # Check if server binary exists
    if [ ! -f "./http_server" ]; then
        echo "Error: http_server binary not found. Please compile first with 'make'"
        exit 1
    fi
    
    # Set up trap to clean up on exit
    trap stop_server EXIT
    
    # Start server
    if ! start_server; then
        exit 1
    fi
    
    echo ""
    echo "Running tests..."
    echo "================"
    
    # Test endpoints
    test_endpoint "http://localhost:$SERVER_PORT/ping" "Ping endpoint"
    test_endpoint "http://localhost:$SERVER_PORT/cgi/time" "System time endpoint"
    test_endpoint "http://localhost:$SERVER_PORT/cgi/status" "System status endpoint"
    test_endpoint "http://localhost:$SERVER_PORT/cgi/version" "Version endpoint"
    test_endpoint "http://localhost:$SERVER_PORT/cgi/echo" "Echo endpoint" "POST"
    
    echo ""
    echo "Tests completed!"
}

# Run main function
main "$@"